package com.hoolai.db;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

/**
 * 
 * @author liyuwei
 *
 */
@Component
@PropertySources(value = { @PropertySource("db.properties") })
public class DynamicDataSource extends AbstractRoutingDataSource {
	@Value("${jdbc.driver.default}")
	private String driver_default;
	@Value("${jdbc.url.default}")
	private String url_default;
	@Value("${jdbc.username.default}")
	private String username_default;
	@Value("${jdbc.password.default}")
	private String password_default;

	@Override
	protected Object determineCurrentLookupKey() {
		return CustomerContextHolder.getCustomerType();
	}

	@PostConstruct
	public void init() {

		Map<Object, Object> dataSourceMap = new HashMap<>();
		initDataSource(dataSourceMap);
	}

	public void initDataSource(Map<Object, Object> dataSourceMap) {
		dataSourceMap.put(CustomerContextHolder.DATA_SOURCE_DEFAULT,
				createDataSource(driver_default, url_default, username_default, password_default));
		this.setTargetDataSources(dataSourceMap);
		super.setLenientFallback(false);
		this.setDefaultTargetDataSource(dataSourceMap.get(CustomerContextHolder.DATA_SOURCE_DEFAULT));
	}

	/**
	 * centre DB data source.used for storing other DBs' configuration
	 */
	private DataSource createDataSource(String driver, String url, String username, String password) {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}
}
